package com.sincetimes.game.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;

public class CSVManager {

	private static CSVManager manager = new CSVManager();
	private HashMap<String, String> configMap = new HashMap<String, String>();
	private Log logger = LogFactory.getLog(CSVManager.class);

	public static CSVManager getInstance() {
		return manager;
	}
	
	private CSVManager() {
		loadConfig();
	}

	private String getConfig(String name) {
		return configMap.get(name);
	}
	
	public String getIp(Integer version, Boolean isdebug) {
		String value = getConfig("" + version + "_" + isdebug);
		
		if (value == null || value == "")
		{
			value = getConfig("*" + "_" + isdebug);
		}
				
		String item[] = value.split(":");
		if (item.length == 2)
		{
			return item[0];
		}			
				
		return "";
	}

	public String getPort(Integer version, Boolean isdebug) {
		String value = getConfig("" + version + "_" + isdebug);
		
		if (value == null || value == "")
		{
			value = getConfig("*" + "_" + isdebug);
		}
				
		String item[] = value.split(":");
		if (item.length == 2)
		{
			return item[1];
		}			
				
		return "";
	}
	
	private void setConfig(String name, String value) {
		configMap.put(name, value);
	}
	
	public void loadConfig() {
		 try {			 
			 ClassPathResource resource = new ClassPathResource("serverconfig.csv");
			 //logger.info("path : " + resource.getURI().getPath());
	         BufferedReader reader = new BufferedReader(new FileReader(resource.getURI().getPath()));
	         reader.readLine();//第一行信息，为标题信息，不用,如果需要，注释掉
	         String line = null;
	         while((line=reader.readLine())!=null){
	             String item[] = line.split(",");//CSV格式文件为逗号分隔符文件，这里根据逗号切分
	             if (item.length == 4)
	             {
	            	 logger.info("key : " + (item[0] + "_" + item[1]) + " val : " + (item[2] + ":" + item[3]));
		             setConfig(item[0] + "_" + item[1], item[2] + ":" + item[3]);	            	 
	             }
	             else
	             {
	            	 logger.error("csv format error");	            	 
	             }
	         }
	         reader.close();
	     } catch (Exception e) {
	         e.printStackTrace();
	     }
	}

}
